package com.mjh.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.db.Session;
import cn.hutool.http.server.HttpServerRequest;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mjh.exception.ClientParameterException;
import com.mjh.mapper.ApplicantMapper;
import com.mjh.pojo.Applicant;
import com.mjh.pojo.dto.ApplicantDto;
import com.mjh.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;
import java.util.HashMap;

/**
 *
 * 申请用户表 前端控制器
 *
 *
 * @author MJH
 * @since 2021-12-03
 */
@RestController
@RequestMapping("/applicant")
public class ApplicantController {

    @Autowired
    private ApplicantMapper applicantMapper;


    @Autowired
    private HttpServletRequest request;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;






    /**
     *  申请人登录接口
     * @param loginUser
     * @return  token
     */
    @PostMapping("/login")
    public ResponseEntity<String> login(@RequestBody ApplicantDto loginUser){

        if(BeanUtil.isEmpty(loginUser)) throw  new ClientParameterException("登录用户参数为空");

        QueryWrapper<Applicant> wrapper = new QueryWrapper<>();
        wrapper.eq("username",loginUser.getPhone());
        Applicant applicant = applicantMapper.selectOne(wrapper);

        //判断密码
        if (applicant==null ||
                !applicant.getPassword().equals(DigestUtils.md5DigestAsHex(loginUser.getPassword().getBytes())))
            throw new ClientParameterException("用户名或密码错误");

        //获取验证key
        String captchaKey = request.getHeader("code");
        if (captchaKey==null) throw  new ClientParameterException("验证码过期");

        //获取验证码
        String captcha =(String) redisTemplate.opsForValue().get(captchaKey);
        //校验验证码
        if (captcha==null || !captcha.equals(loginUser.getCode())) throw  new ClientParameterException("验证码不正确");
        //清除验证码
        redisTemplate.delete(captchaKey);

        HashMap<String, Object> map = new HashMap<>();
        map.put("userId",applicant.getId());
        map.put("name",applicant.getName());

        String token = JwtUtil.createToken(map);


        return ResponseEntity.ok(token);
    }


    /**
     * 申请人注册
     * @param registerUser  注册用户
     * @return
     */
    @PostMapping("/register")
    public ResponseEntity<String> register(@RequestBody ApplicantDto registerUser){

        if (BeanUtil.isEmpty(registerUser,"code")) throw  new ClientParameterException("注册用户参数为空");

        QueryWrapper<Applicant> wrapper = new QueryWrapper<>();
        wrapper.eq("phone",registerUser.getPhone());
        Applicant applicant = applicantMapper.selectOne(wrapper);

        if (applicant!=null)  throw  new ClientParameterException("手机号已被注册使用");
        registerUser.setPassword(DigestUtils.md5DigestAsHex(registerUser.getPassword().getBytes()));


        Applicant applicantRegister = BeanUtil.copyProperties(registerUser, Applicant.class, "code");
        applicantRegister.setUsername(registerUser.getPhone());
        applicantMapper.insert(applicantRegister);

        return ResponseEntity.ok("ok");

    }


    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("/userinfo")
    public ResponseEntity<Applicant> getUserInfo(){
        Integer userId =(Integer) JwtUtil.getPayload(request, "userId");
        Applicant applicant = applicantMapper.selectById(userId);
        applicant.setPassword("");

        return ResponseEntity.ok(applicant);
    }
}
